package com.utry.netty.websocket;


import com.utry.netty.intf.ConnectClientCallback;
import com.utry.netty.intf.MessageClientCallback;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class NettyStocktakingUtil {

    private volatile static NettyStocktakingUtil instance = null;
    private NettyStocktakingClient client;

    public static NettyStocktakingUtil getInstance() {
        if (instance == null) {
            synchronized (NettyStocktakingUtil.class) {
                if (instance == null) {
                    instance = new NettyStocktakingUtil();
                }
            }
        }
        return instance;
    }

    /**
     * Netty连接
     *
     * @param connectClientCallback
     */
    public void nettyConnect(final ConnectClientCallback connectClientCallback) {
        client = NettyStocktakingClient.getInstance();
//        client.setIPAndPort(ip, port);
        client.connectNetty();
        client.setConnectClientCallback(connectClientCallback);
    }

    /**
     * 向后台发送数据
     *
     * @param data
     */
    public void setNettyPost(String data) {
        try {
            Channel channel = NettyStocktakingClient.getChannel();
            if (channel == null) {
            } else {
                TextWebSocketFrame frame = new TextWebSocketFrame(data);
                channel.writeAndFlush(frame).addListener((ChannelFutureListener) channelFuture -> {
                    if (channelFuture.isSuccess()) {
                        System.out.println("消息发送成功，发送的消息是：" + data);
                    } else {
                        System.out.println("消息发送失败 " + channelFuture.cause().getMessage());
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 后台数据监听
     *
     * @param messageClientCallback
     */
    public void setMessageClientCallback(MessageClientCallback messageClientCallback) {
        try {
            if (client != null) {
                client.setMessageClientCallback(messageClientCallback);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开连接
     */
    public void destroy() {
        if (client != null) {
            client.destroy();
        }
    }
}
